package com.hq.http;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.paging.ListenableFuturePagingSource;
import androidx.paging.PagingState;

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;

import java.io.IOException;

import retrofit2.HttpException;

/**
 * 分页 数据源配置
 * 泛型 Records ：数据实体类
 * 泛型 Integer ：分页页码
 */
public class BaseDataSource extends ListenableFuturePagingSource<Integer,Records> {
    private IhttpService api;//获取网络接口数据
    private ListeningExecutorService pool;//线程池

    public BaseDataSource(IhttpService api, ListeningExecutorService pool) {
        this.api = api;
        this.pool = pool;
    }

    /**
     * 错误 返回
     * @param pagingState
     * @return
     */
    @Nullable
    @Override
    public Integer getRefreshKey(@NonNull PagingState<Integer, Records> pagingState) {
        Integer anchorPosition = pagingState.getAnchorPosition();
        if (anchorPosition == null) {
            return null;
        }

        LoadResult.Page<Integer, Records> anchorPage = pagingState.closestPageToPosition(anchorPosition);
        if (anchorPage == null) {
            return null;
        }

        Integer prevKey = anchorPage.getPrevKey();
        if (prevKey != null) {
            return prevKey + 1;
        }

        Integer nextKey = anchorPage.getNextKey();
        if (nextKey != null) {
            return nextKey - 1;
        }

        return null;
    }



    /**
     * 加载数据
     * @param loadParams
     * @return 分页数据
     */
    @NonNull
    @Override
    public ListenableFuture<LoadResult<Integer, Records>> loadFuture(@NonNull LoadParams<Integer> loadParams) {
        Integer next = loadParams.getKey();
       //第一页
        if (next == null) {
            next = 1;
        }else {
           next= loadParams.getKey()+1;
        }
        ListenableFuture<LoadResult<Integer, Records>> pageFuture = Futures.transform(api.ResultPagVideo(next,Records.pageSize),this::toLoadResult, pool);
        ListenableFuture<LoadResult<Integer, Records>> partialLoadResultFuture=Futures.catching(pageFuture, HttpException.class,LoadResult.Error::new, this.pool);

        return Futures.catching(partialLoadResultFuture,IOException.class, LoadResult.Error::new, this.pool);
    }



    private LoadResult<Integer,Records> toLoadResult(@NonNull Result.PagData response) {
        Integer nextPage =null;//下一页
    if (response.getPageNum()<response.getPages()) {
            nextPage=response.getPageNum();
        }

        LoadResult<Integer,Records> res= new LoadResult.Page<>(response.getRecords()
                , null,nextPage,
                LoadResult.Page.COUNT_UNDEFINED,
                LoadResult.Page.COUNT_UNDEFINED);
        return res;
    }
}
